package cn.com.manager.controller;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.com.manager.page.PageInfo;
import cn.com.manager.pojo.Demo;
import cn.com.manager.pojo.JsonResult;
import cn.com.manager.pojo.Menu;
import cn.com.manager.pojo.Role;
import cn.com.manager.pojo.User;
import cn.com.manager.service.SystemService;

@Controller
public class SystemController {
	private static final Logger logger = LoggerFactory.getLogger(SystemController.class);
	@Autowired
	private SystemService systemService;
	
	private String go = "/main";

	@RequestMapping("/login")
	public String login(Model model, HttpServletRequest request) throws UnsupportedEncodingException{
		String kickout = request.getParameter("kickout");
		if (StringUtils.isNotBlank(kickout)){
			//判断账号是否被顶牛
			model.addAttribute("message",kickout);
		}
		return "system/loginPage";
	}
	
	/**
	 * 注册页跳转
	 * @param user
	 * @return
	 */
	@RequestMapping("/register")
	public String register(@ModelAttribute ("user")User user){
		return "system/register";
	} 
	
	@RequestMapping("/main")
	public String main(){
		return "index";
	}

	@RequestMapping("/menuTree")
	@ResponseBody
	public List<Map<String, Object>> menuTree(){
		List<Map<String, Object>> maps = systemService.searchMenu();
		return maps;
	}
	
	@RequestMapping("/userRegister")
	public String userRegister(@ModelAttribute("user")User user,RedirectAttributes redirectAttributes){
		User newUser = systemService.addOfUser(user);
		if(StringUtils.isBlank(newUser.getId())){
			redirectAttributes.addFlashAttribute("message","注册失败！");
			return "redirect:/register";
		}else{
			redirectAttributes.addFlashAttribute("message","注册成功,请登录！");
			return "redirect:/login";	
		}
	}

	@RequestMapping("/userLogin")
	public String userLogin(@RequestParam(value = "username") String username,
			@RequestParam(value = "password") String password,RedirectAttributes redirectAttributes) {
		Subject subject = SecurityUtils.getSubject();
		try{
			if(!subject.isAuthenticated()){
				UsernamePasswordToken token = new UsernamePasswordToken(username,password);
				subject.login(token);
			}
		}catch(UnknownAccountException e){
			redirectAttributes.addFlashAttribute("message", "用户不存在");
			go = "/login";
			return "redirect:"+go;
		}catch(LockedAccountException e){
			redirectAttributes.addFlashAttribute("message","该账户已锁");
			go = "/login";
			return "redirect:"+go;
		}catch(ExcessiveAttemptsException e){
			redirectAttributes.addFlashAttribute("message","密码尝试次数过多，请稍后再试！");
			go = "/login";
			return "redirect:"+go;
		}catch(IncorrectCredentialsException e){
			redirectAttributes.addFlashAttribute("message","账户或密码错误！");
			go = "/login";
			return "redirect:"+go;
		}catch(Exception e){
			logger.error("登录错误,{}",e);
			redirectAttributes.addFlashAttribute("message","未知异常");
			go = "/login";
			return "redirect:"+go;
		}
		go = "/main";
		return "redirect:"+go;
	}

	@RequestMapping("/menuInit")
	public String menuInit(@ModelAttribute Menu menu,Model model){
		List<Menu> menus = systemService.searchMenuByLevel(0,null);
		model.addAttribute("level1Menus",menus);
		return "system/menu";
	}

	@RequestMapping("/menuGet")
	@ResponseBody
	public List<Menu> menuGet(@ModelAttribute("menu") Menu menu){
		List<Menu> menus = systemService.searchMenuByLevel(1,menu.getId().trim());
		return menus;
	}

	@RequestMapping("/menuEdit")
	@ResponseBody
	public Menu menuEdit(@ModelAttribute("menu") Menu menu){
		return systemService.searchMenuById(menu.getId().trim());
	}

	@RequestMapping("/menuSave")
	public String menuSave(@ModelAttribute("menu") Menu menu,RedirectAttributes redirectAttributes){
		int i = systemService.saveMenuInfo(menu);
		if(i>0){
			redirectAttributes.addFlashAttribute("message","保存成功！");
			return "redirect:/menuInit";
		}else{
			redirectAttributes.addFlashAttribute("message","保存失败！");
			return "redirect:/menuInit";
		}
	}

	@RequestMapping("/menuDel")
	@ResponseBody
	public String  menuDel(@ModelAttribute("menu") Menu menu){
		systemService.delMenuInfo(menu.getId());
		return "删除成功！请刷新！";
	}
	
	@RequestMapping(value="/role/editRole")
	public String editRole(@ModelAttribute("role")Role role,Model model){
		if(StringUtils.isNotBlank(role.getRoleId())){
			role = systemService.searchRoleById(role.getRoleId());
		}
		model.addAttribute("role",role);
		return "system/editRole";
	}
	@RequestMapping("/role/saveRoleInfo")
	public String saveRoleInfo(@ModelAttribute("role")Role role, RedirectAttributes redirectAttributes){
		int num = systemService.saveRoleInfo(role);
		if (num > 0) {
			redirectAttributes.addFlashAttribute("successMsg", "保存成功！");
		} else {
			redirectAttributes.addFlashAttribute("errorMsg", "保存失败！");
		}
		return "redirect:/role/search";
	}
	
	@RequestMapping(value="/role/search")
	public String searchRoleList(@ModelAttribute("role")Role role,PageInfo pageInfo,Model model){
		List<Role> roleList = systemService.search(role, pageInfo);
		model.addAttribute("recordList",roleList);
		model.addAttribute("role",role);
		return "system/roleList";
	}
	
	@RequestMapping("/role/removeRecord")
	@ResponseBody
	public JsonResult removeRecord(@ModelAttribute(value="role") Role role) {
		int result = systemService.removeRoleInfo(role.getRoleId());
		JsonResult jsonResult = new JsonResult();
		if (result > 0) {
			jsonResult.setCode(0);
			jsonResult.setMessage("删除成功");
		}
		return jsonResult;
	}
	
	@RequestMapping("/user/search")
	public String userSearch(@ModelAttribute("user")User user,PageInfo pageInfo,Model model){
		List<User> userList = systemService.search(user, pageInfo);
		model.addAttribute("recordList",userList);
		model.addAttribute("user",user);
		return "system/userList";
	}
	
	@RequestMapping("/user/removeRecord")
	@ResponseBody
	public JsonResult removeRecord(@ModelAttribute(value="user") User user) {
		int result = systemService.removeUserInfo(user.getId());
		JsonResult jsonResult = new JsonResult();
		if (result > 0) {
			jsonResult.setCode(0);
			jsonResult.setMessage("删除成功");
		}
		return jsonResult;
	}
	
	@RequestMapping("/user/editUser")
	public String editUser(@ModelAttribute(value="user") User user,Model model){
		if(StringUtils.isNotBlank(user.getId())){
			user = systemService.searchUserById(user.getId());
		}
		model.addAttribute("user",user);
		return "system/editUser";
	}
	
	@RequestMapping("/user/saveUser")
	public String saveUser(@ModelAttribute(value="user") User user,RedirectAttributes redirectAttributes){
		int num = systemService.saveUserInfo(user);
		if (num > 0) {
			redirectAttributes.addFlashAttribute("successMsg", "保存成功！");
		} else {
			redirectAttributes.addFlashAttribute("errorMsg", "保存失败！");
		}
		return "redirect:/user/search";
	}
	
	@RequestMapping("/user/bindRole")
	public String userBindRole(@ModelAttribute(value="user")User user,Model model){
		user = systemService.searchUserById(user.getId());
		List<Role> roleList = systemService.search(new Role(), null);
		model.addAttribute("roleList",roleList);
		model.addAttribute("user",user);
		return "system/bindRole"; 
	}
	
	@RequestMapping("/user/saveBindRoles")
	public String saveBindRole(@ModelAttribute("user")User user,@RequestParam(value="roleIds",required=false)String roleIds,RedirectAttributes redirectAttributes){
		systemService.saveUserBindRoles(user.getId(), roleIds);
        redirectAttributes.addFlashAttribute("successMsg", "保存成功！");
		return "redirect:/user/search";
	}
	
	
}
